/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useState } from 'react';
import './index.scss';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';

type Params = {
  curves: string[];
  offset: number;
  isNeedClosed: boolean;
  isNeedArc: boolean;
  normal?: string;
};

type CurveType = {
  curve: pickedLineData;
};

type FormDataType = {
  curves: Array<CurveType>;
  offset: number;
  isNeedClosed?: boolean;
  isNeedArc?: boolean;
  normal?: pickedLineData | pickedFaceData;
};

// 偏移曲线
// 暂时去除拔模方向设置（保留代码、参数、隐藏UI设置）
function CmdOffsetCurve({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    curves: [{ curve: null }],
    offset: 0,
    isNeedClosed: false,
    isNeedArc: false,
  };
  const [formData, setFormData] = useState<FormDataType>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    } else {
      const params = props.params as Params;
      const { curves, offset, isNeedClosed, isNeedArc, normal } = params;

      await initEditDependency([...params.curves, normal]);

      setFormData({
        curves: curves.map((curve) => ({
          curve: picker.generatePickObjByPickID(curve) as pickedLineData,
        })),
        offset,
        isNeedClosed,
        isNeedArc,
        normal: picker.generatePickObjByPickID(normal) as
          | pickedLineData
          | pickedFaceData,
      });
    }
  }, []);

  const isFormDataValid = () => {
    const { curves, offset } = formData;
    return !(
      (
        curves.length < 1 ||
        curves.some((p) => p?.curve == null) ||
        offset == null ||
        offset == 0
      )
      // 暂时去除拔模方向设置
      // || (normal == null)
    );
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-offset-curved', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = async (preview: boolean) => {
    const { curves, offset, isNeedClosed, isNeedArc, normal } = formData;
    const curvesArr = curves.map((item) => item.curve?.edgeId);

    await confirmCommand(
      {
        type: 'Offset',
        a: {
          curves: curvesArr,
          offset: (normal as pickedLineData)?.assisObj?.isReversed
            ? -offset
            : offset,
          normal: getIdOfPickedObj(normal),
          isNeedClosed,
          isNeedArc,
        },
      },
      preview,
    );
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curves: {
        type: 'array',
        items: {
          type: 'object',
          title: '曲线',
          properties: {
            curve: {
              type: 'string',
              title: '曲线',
              format: PickInputRJSFFormat.PickCurve,
            },
          },
        },
      },
      offset: {
        type: 'number',
        title: '偏移',
        default: 0,
        format: NumberInputFormat.Length,
      },
      // 暂时去除拔模方向设置，但保留代码
      // normal: {
      //   type: 'string',
      //   format: PickInputRJSFFormat.PickDirection,
      // },
      isNeedClosed: {
        type: 'boolean',
        title: '是否与当前曲线形成闭合',
        default: true,
      },
      isNeedArc: {
        type: 'boolean',
        title: '是否与相邻线使用圆角链接',
        default: true,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      submitLoading={isLoading}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
      extraUiSchema={{
        'ui:options': {
          classNames: 'command-form command-form_cmd-curve',
        },
        curves: {
          items: {
            curve: {
              'ui:autofocus': true,
              'ui:placeholder': '请输入曲线',
            },
          },
        },
        // 暂时去除拔模方向设置，但保留代码
        // normal: {
        //   'ui:placeholder': '请输入拔模方向',
        //   'ui:options': {
        //     label: false,
        //     showArrow: true,
        //     curveReversable: true,
        //   },
        // },
      }}
    />
  );
}

export const cmdOffsetCurve: CurvedBaseCommand = {
  id: 'CmdOffsetCurve',
  label: 'command.offset-curve',
  icon: 'commands/curved/offset-curve',
  create: (label, onClose, props) => (
    <CmdOffsetCurve
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
